package com.itheima.d5_resource;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/*
     目标：掌握释放资源的方式。
 */
public class Test2 {
    public static void main(String[] args)  {
        String source = "D:\\autoML 工具.md";
        String target = "D:\\codes\\copyfile.md";

        long start = System.currentTimeMillis();
        copyFile(source, target);
        long end = System.currentTimeMillis();
        System.out.println("耗时：" + (end - start));
    }

    public static void copyFile(String sourceFilePath, String targetPath) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            // 1. 创建流对象
            fis = new FileInputStream(sourceFilePath);
            fos = new FileOutputStream(targetPath);

            // 2. 写入数据
            int len = -1;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }
        } catch (Exception io) {
            System.out.println("io 异常： " + io.getMessage());
        } finally {
            // 3. 关闭流
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                    System.out.println("关闭一次：" + e.getMessage());
                }
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    System.out.println("关闭一次：" + e.getMessage());
                }
            }
        }
    }
}
